package helper;

import java.security.PrivateKey;
import java.security.Signature;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

public class SignatureHelper {
	/**
	 * 得到签名内容
	 * @param parameters 参数列表
	 * */
	public static String GetSignatureContent(HashMap<String, String> parameters) {
		StringBuilder sb = new StringBuilder();
		List<String> keyList = new ArrayList<>(parameters.keySet());
		Collections.sort(keyList);
		for(int i = 0; i < keyList.size(); i++) {
            String key = keyList.get(i);
            String value = parameters.get(key);
            sb.append(i == 0 ? "" : "&").append(key).append("=").append(value);
		}
		return sb.toString();
	}
	/**
	 * 签名
	 * @param content 带签名内容
	 * @param privateKeyPem 私钥
	 * @return 签名值的 Base64 字符串
	 * */
	public static String Sign(String content, String privateKeyPem) {
		try {
			PrivateKey privateKey = RSAHelper.getPrivateKey(privateKeyPem);
			Signature signature = Signature.getInstance(util.Constants.MD5_WITH_RSA);
			signature.initSign(privateKey);
			signature.update(content.getBytes(util.Constants.DEFAULT_CHARSET));
			byte[] signed = signature.sign();
			return new String(Base64.getEncoder().encode(signed));
		}catch (Exception e) {
			// TODO: handle exception
			throw new RuntimeException("\n签名有异常，content=" + content + " privateKeySize=" + privateKeyPem.length() + " reason=" + e.getMessage());
		}
	}
}
